package com.fastplatform.service;

import cn.dev33.satoken.stp.StpUtil;
import com.fastplatform.dto.LoginRequest;
import com.fastplatform.dto.UserInfo;
import com.fastplatform.entity.User;
import com.fastplatform.repository.UserRepository;

import org.mindrot.jbcrypt.BCrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

@Service
public class AuthService {
    
    @Autowired
    private UserRepository userRepository;
    
    @Autowired
    private UserService userService;
    
    public Map<String, Object> login(LoginRequest loginRequest, String clientIp) {
        // 查找用户
        Optional<User> userOpt = userRepository.findByUsernameAndDeletedFalse(loginRequest.getUsername());
        if (userOpt.isEmpty()) {
            throw new RuntimeException("用户名或密码错误");
        }
        
        User user = userOpt.get();
        
        // 验证密码
        if (!BCrypt.checkpw(loginRequest.getPassword(), user.getPassword())) {
            throw new RuntimeException("用户名或密码错误");
        }
        
        // 验证用户状态
        if (user.getStatus() != 1) {
            throw new RuntimeException("用户已被禁用");
        }
        
        // 更新登录信息
        user.setLastLoginTime(LocalDateTime.now());
        user.setLastLoginIp(clientIp);
        userRepository.save(user);
        
        // 登录
        StpUtil.login(user.getId());
        
        // 获取用户信息
        UserInfo userInfo = userService.getUserInfo(user.getId());
        
        // 返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("token", StpUtil.getTokenValue());
        result.put("userInfo", userInfo);
        
        return result;
    }
    
    public void logout() {
        StpUtil.logout();
    }
    
    public UserInfo getCurrentUserInfo() {
        Long userId = StpUtil.getLoginIdAsLong();
        return userService.getUserInfo(userId);
    }
} 